package gulimall.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import java.util.Arrays;
import java.util.List;

/**
 * @author HLF
 * @date 2022/8/6 11:12
 */
@Controller
public class HelloController {

    @Value("${sso.server.url}")
    private String serverUrl;

    @Value("${sso.redirect.url}")
    private String redirectUrl;


    @GetMapping("/hello")
    @ResponseBody
    public String hello() {
        return "hello";
    }


    /**
     * 受保护的资源，必须登录后才能访问
     *
     * @param session
     * @return
     */
    @GetMapping("/employees")
    public ModelAndView employees(HttpSession session, @RequestParam(value = "token",required = false) String token) {
        ModelAndView modelAndView = new ModelAndView();

        if (StringUtils.hasText(token)) {
            //去认证服务器获取当前token的真正对应的用户信息
            RestTemplate restTemplate = new RestTemplate();
            ResponseEntity<String> forEntity = restTemplate.getForEntity("http://ssoserver.com:6080/userInfo?token=" + token, String.class);
            String body = forEntity.getBody();//获取响应的内容
            session.setAttribute("loginUser",body);
        }

        Object loginUser = session.getAttribute("loginUser");

        if (loginUser == null) {
            //跳转到登录服务器进行登录
            modelAndView.setViewName("redirect:" + serverUrl + "?redirect_url=" + redirectUrl);
            return modelAndView;
        } else {
            List<String> list = Arrays.asList("张三", "李四");
            modelAndView.setViewName("list");
            modelAndView.addObject("employees", list);
            return modelAndView;
        }

    }
}
